<script setup>
import { onMounted, onUnmounted, onBeforeMount,watchEffect,ref } from 'vue'
import { NavBar, Sticky, PullRefresh } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import { userStore } from '@/store/user'
import { enumStore } from '@/store/enum'
import { refreshStore } from '@/store/refresh'
import { storeToRefs } from 'pinia'
import Toast from '@/components/toast/index.js'
import nativeApi from '@/utils/native'
import KefuFrame from './kefu.vue'
import dsBridge from 'dsbridge'
import Utility from '@/utils/utility'
import commonModel from '@/http/modules/common.js'
import { enumDslList } from '@/enum/enumDslList'

const route = useRoute()
const router = useRouter()
const user_store = userStore()
const enum_store = enumStore()
const refresh = refreshStore()
const { userInfo, supplier_pay_enable } = storeToRefs(user_store)
const { enumDslInfo } = storeToRefs(enum_store)
const { disabled } = storeToRefs(refresh)
const isGetVaAccount = ref(false) //是否已经获取过va账户
function handleBack() {
  if (window.history.length === 1 || route.meta.exitWeb) {
    // 返回app
    nativeApi.exitWeb()
  } else if (route.meta.backHome) {
    router.replace('/')
  } else if (route.meta.appointUrl) {
    router.push(route.meta.appointUrl)
  } else {
    router.go(-1)
  }
}
function onRefresh() {
  window.location.reload()
}
function saveSource() {
  const url = new URL(window.location.href)
  const searchParams = new URLSearchParams(url.search)
  for (const s of searchParams) {
    if (s[0] === 'source') {
      sessionStorage.source = s[1]
    }
  }
}
function changeKjtToken(appToken) {
  let searchParams = Utility.getSearchParams()
  if (appToken) {
    commonModel
      .gatewayApi({
        bizContent: {
          appToken: appToken,
          source: searchParams.source, //埋点记录来源
        },
        service: 'cross_app_login_register',
        version: '1.0.0',
      })
      .then((res) => {
        res = res || {}
        //缓存token memberId
        sessionStorage.setItem('token', res.token)
        sessionStorage.setItem('memberId', res.memberId)
        sessionStorage.setItem('isFromApp', '1') // ”1“表示是从APP端下
        // APP 进入记录来源
        if (searchParams.source) {
          sessionStorage.setItem('source', searchParams.source)
        }
      })
  }
}
function getAppToken() {
  let searchParams = Utility.getSearchParams()
  if (searchParams.token) {
    sessionStorage.setItem('token', searchParams.token)
  } else {
    //获取app 登录信息换快捷通token
    if (dsBridge && !sessionStorage.token) {
      let appToken = dsBridge.call('getTokenSync')
      changeKjtToken(appToken)
    }
  }
}
function clearAccountInfo() {
  //删除缓存
  Utility.clearCompany()
  sessionStorage.removeItem('token')
  sessionStorage.removeItem('companyType')
  sessionStorage.removeItem('memberId')
  sessionStorage.removeItem('isFromApp')
  sessionStorage.removeItem('mainPage')
  sessionStorage.removeItem('tradePage')
  sessionStorage.removeItem('contractPage')
  sessionStorage.removeItem('supplierPayPage')
  sessionStorage.removeItem('source')
  sessionStorage.removeItem('memberName')
}
onUnmounted(() => {
  clearAccountInfo()
})
onBeforeMount(() => {
  getAppToken()
})
function checkSupplierConfig() {
  //供应商付款tab显示开关
  commonModel
    .gatewayApi({
      bizContent: {
        enumType: 'SUPPLIER_CONFIG',
      },
      service: 'unionma_query_enum_data',
      version: '1.0.0',
    })
    .then((res) => {
      if (res && res.supplier_pay_enable === '0') {
        supplier_pay_enable.value = false
      }
    })
}
function getEnumsList() {
  commonModel
    .gatewayApi({
      bizContent: {
        enumDslList,
      },
      service: 'cb_trade_enums_list',
      version: '1.0.0',
    })
    .then((res) => {
      if (res) {
        for (const key in res) {
          if (res[key] && res[key].length) {
            if(key === 'CurrencyType'){
              res[key] = res[key].filter(v=>v.value !== 'CNY').map((_) => ({ ..._, name: _.label }))
            }else{
              res[key] = res[key].map((_) => ({ ..._, name: _.label }))
            }
          }
        }
        enumDslInfo.value = res
      }
    })
}
function getVaAccountInfo(){
  commonModel
    .gatewayApi({
      bizContent: {
        token: sessionStorage.token,
      },
      service: 'cb_account_list_query',
      version: '1.0.0',
    })
    .then((res) => {
      //是否有设置交易面膜
      if (res && res.isShortPayPasswordSet) {
        sessionStorage.isShortPayPasswordSet = res.isShortPayPasswordSet
      }

      userInfo.value = res
      if (
        res.permissionStatus === 'false' && //permissionStatus:是否有权限做交易
        window.location.href.includes('/home')
      ) {
        Toast.open({
          type: 'warning',
          title:
            '您的证件已过期，请点击【我的】页面，重新提交有效证件，审核通过即可提现。',
          showCancel: false,
          showClose: false,
          confirmFun: () => {
            Toast.close()
          },
        })
      }
    })
}
watchEffect(()=>{
  const NotGetVaAccountRoutes = ['/prize', '/', '/prizeRule', '/myPrize']
  if (!NotGetVaAccountRoutes.includes(route.path) && !isGetVaAccount.value) {
    isGetVaAccount.value = true
    getVaAccountInfo()
  }
})
onMounted(() => {
  getEnumsList()
  checkSupplierConfig()
  saveSource()
  //获取user信息   
  // if(window.location.pathname !== '/prize'){
  //   getVaAccountInfo()
  // }
})
</script>

<template>
  <Sticky>
    <nav-bar
      v-if="!route.meta.hideNav"
      :title="route.meta.title"
      :left-arrow="!route.meta.hideBack"
      @click-left="handleBack"
    ></nav-bar>
  </Sticky>
  <PullRefresh
    :disabled="route.meta.noRefresh || disabled"
    @refresh="onRefresh"
  >
    <KefuFrame />
    <router-view v-slot="{ Component }">
      <keep-alive>
        <component
          :is="Component"
          :key="route.params.id"
          v-if="route.meta.keep"
        />
      </keep-alive>
      <component :is="Component" :key="route.path" v-if="!route.meta.keep" />
    </router-view>
  </PullRefresh>
</template>

<style scoped lang="scss">
:deep(.van-icon-arrow-left) {
  color: #000;
}
</style>
